package ca.uvic.cs.cogz.mapping.ui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;

import ca.uvic.cs.cogz.mapping.ontology.TransformationEngine;

/**
 * Class for displaying ATL mapping rules as they are generated.
 * 
 * @author seanf
 */
public class ATLRulePanel extends JPanel {
	private static final String NO_RULES_GENERATED = "No rules generated";

	private static final long serialVersionUID = -2433115559485453814L;

	private JEditorPane atlRulesPane;
	
	public ATLRulePanel() {
		init();
	}
	
	public void updateRules() {
		String rules = TransformationEngine.getInstance().getRules();
		if(rules != null) {
			atlRulesPane.setText(rules.replace("<", "&lt;").replace("\n", "<br>").replace("\t", "&nbsp;&nbsp;").replace("rule", "<b>rule</b>").replace("IN", "<b>IN</b>").replace("OUT", "<b>OUT</b>"));
		}
		else {
			atlRulesPane.setText(NO_RULES_GENERATED);
		}
	}
	
	private void init() {
		setLayout(new BorderLayout());
		
		atlRulesPane = new JEditorPane("text/html", NO_RULES_GENERATED);
		JScrollPane scrollPane = new JScrollPane(atlRulesPane, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
		
		add(scrollPane, BorderLayout.CENTER);
		
		JPanel panel = new JPanel();
		JButton transformButton = new JButton("Execute");
		transformButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					String rules = TransformationEngine.getInstance().getRules();
					
					//FileWriter fw = new FileWriter("MyMapping.atl");
					//fw.write(rules);
					//fw.close();
					
					Runtime.getRuntime().exec("c:\\temp\\eclipse\\eclipse.exe");
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
		panel.add(transformButton);
		
		add(panel, BorderLayout.SOUTH);
	}
}
